# -*- coding: utf-8 -*-
# @Time    : 2020/7/17 9:15
# @Author  : ZhaoHexin
# @File    : DecodeSso.py
# @Description  : sso文件解密

import os
import json
import xmltodict
from config import InfoConfig
from CreateSsoFile.BasicMethod import BasicMethod


class DecodeSso:
    def __init__(self):
        self.is_check = InfoConfig.is_check
        self.path = InfoConfig.path
        self.xml_path = InfoConfig.encryption_path

    def decode(self):
        """
        进行数据解密并按照配置生成解密后文件
        :return:
        """
        # 读取文件
        xml_info = self.read_file()
        # 进行解密
        decode_xml = BasicMethod().des_descrypt(xml_info)
        # 进行信息整理
        sort_info = self.sort_information(decode_xml)
        path = ""
        # 判断是否需要创建文件
        if self.is_check:
            self.create_file(decode_xml)
            path = os.path.join(self.path, "mdm_auto_account_decode.xml")
        return {"decode_info": sort_info, "path": path}

    def create_file(self, info):
        """
        生成sso文件
        :return:
        """
        with open(os.path.join(self.path, "mdm_auto_account_decode.xml"), "w", encoding="utf-8") as f:
            f.write(info)

    def read_file(self):
        """
        读取sso文件信息
        :return:
        """
        with open(self.xml_path, "r", encoding="utf-8") as f:
            return f.read()

    def sort_information(self, info):
        """
        整理输出信息
        :return:
        """
        sort_infos = []
        info_ = json.loads(json.dumps(xmltodict.parse(info,encoding="utf-8")))
        for info in info_.get("Accounts").get("AccountInfo") if type (info_.get("Accounts").get("AccountInfo")) == list else [info_.get("Accounts").get("AccountInfo")]:
            sort_infos.append({
                "username": info.get("AccountDisplayName").get("@name"),
                "password": info.get("AccountPwd").get("@pwd"),
                "majorcode": info.get("Major").get("@code"),
                "majorname": info.get("Major").get("@name"),
                "regioncode": info.get("RegionCode").get("@value")[0:len(info.get("RegionCode").get("@value"))-2]
            })
        return sort_infos
